package com.zkhz.base.security.config;

import com.zkhz.base.constant.enums.ErrorStatus;
import com.zkhz.base.exception.BusinessException;
import com.zkhz.base.security.filter.TokenValueFilter;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.security.web.context.SecurityContextPersistenceFilter;

/**
 * spring security 配置
 *
 * @author wuzeqin
 * @date 2020/5/19
 **/
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
@RequiredArgsConstructor
public class MultiSecurityConfigs {

    private final SystemSecurityProperties securityConfig;

    /**
     * 通用配置，登录认证处理、统一错误处理、静态资源免拦截
     */
    @Configuration
    @Order(-500)
    @RequiredArgsConstructor
    class CommonSecurityConfigurer extends WebSecurityConfigurerAdapter {

        private final AuthenticationSuccessHandler authenticationSuccessHandler;
        private final AuthenticationFailureHandler authenticationFailureHandler;
        private final LogoutSuccessHandler logoutSuccessHandler;

        @Override
        public void configure(HttpSecurity http) throws Exception {
            http.requestMatchers().antMatchers("/error", "/login", "/logout", "/login/**", "/logout/**")
                .and().authorizeRequests().anyRequest().permitAll()
                .and().formLogin().permitAll().successHandler(authenticationSuccessHandler).failureHandler(authenticationFailureHandler)
                .and().logout().permitAll().logoutSuccessHandler(logoutSuccessHandler)
                .and().csrf().disable().cors()
                .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        }

        @Bean   //把AuthenticationManager暴露出来，以便共同使用
        @Override
        protected AuthenticationManager authenticationManager() throws Exception {
            return super.authenticationManager();
        }

        @Override
        public void configure(WebSecurity web) {
            web.ignoring().antMatchers("/doc.html/**", "/swagger-resources/**", "/webjars/**", "/v2/api-docs/**", "/css/**", "/js/**", "/images/**");
            web.ignoring().antMatchers(securityConfig.getWebPermitUrls());
        }
    }

    /**
     * 资源权限配置，JWT模式
     */
    @Configuration
    @EnableResourceServer
    @RequiredArgsConstructor
    class JwtServerConfigurer extends ResourceServerConfigurerAdapter {

        @Override
        public void configure(ResourceServerSecurityConfigurer resources) {
            configureResourceServerSecurity(resources);
        }

        @Override
        public void configure(HttpSecurity http) throws Exception {
            String[] httpPermitUrls = securityConfig.getHttpPermitUrls();   //白名单url
            String[] antPatterns = ArrayUtils.addAll(httpPermitUrls, securityConfig.getJwt().getUrls());
            http.requestMatchers().antMatchers(antPatterns)  //合并
                .and().authorizeRequests().antMatchers(httpPermitUrls).permitAll().anyRequest().authenticated()
                .and().cors()
                .and()
                .addFilterAfter(new TokenValueFilter(), SecurityContextPersistenceFilter.class);
        }

    }

    private static void configureResourceServerSecurity(ResourceServerSecurityConfigurer resources) {
        resources.authenticationEntryPoint(((request, response, authException) -> {   //认证异常
            throw new BusinessException(ErrorStatus.A0200, authException.getMessage(), authException);
        })).accessDeniedHandler(((request, response, authException) -> {   //权限异常
            throw new BusinessException(ErrorStatus.A0301, authException.getMessage(), authException);
        }));
    }

}
